<template>
  <!--首页地图-->
  <div id="Mapcontainer" class="home-map-container"></div>
</template>

<script>
import * as AMapLoader from "@amap/amap-jsapi-loader";
export default {
  data() {
    return {};
  },
  mounted() {

      this.createMap();
  },
  methods: {
    /**初始化 */
    init() {
      this.map_light_ratio = 17 / this.max_zoom;
    },

    /**获取灯杆 */
    getLamppost() {
      this.apiHomeService.getLamppost({}).subscribe((res) => {
        res.data.forEach((item) => {
          let num = Math.floor(Math.random() * 4);
          item.type = num;
        });
        this.lamppost_list = res.data;
        this.loading = true;
        this.createMap();
      });
    },

    /**
     * 创建地图
     */
    createMap() {
      const self = this;
      const center_xy = {x:116.205467,y:39.907761}//this.mapUtil.getCenter(this.lamppost_list);
      AMapLoader.load({
        key: "6027cc22082e43c4862d5466bb343740", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        AMapUI: {
          // 是否加载 AMapUI，缺省不加载
          version: "1.1", // AMapUI 缺省 1.1
          plugins: [], // 需要加载的 AMapUI ui插件
        },
        Loca: {
          // 是否加载 Loca， 缺省不加载
          version: "1.3.2", // Loca 版本，缺省 1.3.2
        },
      })
        .then((e) => {
          this.AMap = e;
          this.map = new this.AMap.Map("Mapcontainer", {
            pitch: 60, // 地图俯仰角度，有效范围 0 度- 83 度
            viewMode: "3D", // 地图模式
            zoom: 19, //最高级19级
            //layers:[{}],
            center: [center_xy.x, center_xy.y], //中心点坐标
            //zoomEnable:false,  //禁止缩放
            //dragEnable: false, //禁止拖动
            turboMode: false,
            showIndoorMap: false,
            defaultCursor: "pointer",
            showBuildingBlock: false,
            zooms: [1, 20],
            showLabel: false,
            rotation: -45,
            forceVector: true,
          });
          //this.map.setMapStyle('amap://styles/859c6c9cd450052bcffe567687ee353d'); //自定义风格
          this.map.setMapStyle("amap://styles/darkblue"); //官方可选风格

          this.map.on("click", function (e) {
            //如果有选中，恢复默认效果
            if (self.curr_viaMarker) {
              self.curr_viaMarker.setAnimation("AMAP_ANIMATION_NONE");
              self.curr_viaMarker = null;
            }
            self.homeService.set({ type: "map" });
          });

          //放大缩小
          this.AMap.event.addListener(this.map, "zoomend", function (e) {
            //获取当前地图层级
            let zoom = self.map.getZoom();
            //相对比例
            self.map_light_ratio = zoom / self.max_zoom;
            let l = Math.floor(118 * self.map_light_ratio);
            let r = Math.floor(172 * self.map_light_ratio);
            let l_p = Math.floor((l / 2) * -1);
            let r_p = Math.floor(r * -1);
            self.map_light_size = [l, r];
            self.map_light_pixel = [l_p, r_p];
            self.map.clearMap();
            //self.setLamppostMap();
          });

          //this.setLamppostMap();
        })
        .catch((e) => {
          console.log("地图", e);
        });
    },

    /**
     * 把灯杆标注在地图上去
     */
    setLamppostMap() {
      let self = this;
      let icons = {};
      this.icon_list.forEach((item, i) => {
        icons["img_" + i] = new this.AMap.Icon({
          image: item,
          size: new this.AMap.Size(...this.map_light_size), //图标大小
          imageSize: new this.AMap.Size(...this.map_light_size),
          scaleFactor: 1, //地图放大一级的缩放比例系数
          maxScale: 20, //最大放大比例
        });
      });

      // 创建 AMap.Icon 实例：
      let markerList = [];
      this.lamppost_list.forEach((item) => {
        let viaMarker = new this.AMap.Marker({
          position: new this.AMap.LngLat(
            item.gateway_location.x,
            item.gateway_location.y
          ),
          // 将一张图片的地址设置为 icon
          icon: icons["img_" + item.type],
          // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
          offset: new this.AMap.Pixel(...self.map_light_pixel),
          //鼠标滑过显示内容
          //title:item.id,
          // 用户自定义属性
          extData: item,
        });

        //点击标注事件
        this.AMap.event.addListener(viaMarker, "click", function (e) {
          //还原上一次点击的点标
          if (self.curr_viaMarker) {
            if (viaMarker.getId() == self.curr_viaMarker.getId()) {
              return;
            }
            //无动画效果
            self.curr_viaMarker.setAnimation("AMAP_ANIMATION_NONE");
          }
          //获取图标经纬度
          //let c = viaMarker.getPosition();
          //获取图标自定义数据
          let extdata = viaMarker.getExtData();
          let lng = extdata.gateway_location.x;
          let lat = extdata.gateway_location.y;
          //地图位移底部可视区域的中间
          let offset_top = Math.floor(self.map.getSize().height - 370) / 2;
          //设置地图旋转
          //self.map.setRotation(0);
          //设置地图中心点
          self.map.setCenter([lng, lat]);
          //设置地图平移
          self.map.panBy(0, offset_top);
          //设置点击点标的样式
          //viaMarker.setIcon(self.map_light);
          //点标弹跳效果
          viaMarker.setAnimation("AMAP_ANIMATION_BOUNCE");
          // 获取自定义属性数据，保存选择点标数据，触发底部展示
          self.homeService.set({
            type: "viaMarker",
            data: viaMarker.getExtData(),
          });
          //把当前点击的标注保存到全局变量
          self.curr_viaMarker = viaMarker;
        });

        markerList.push(viaMarker);
      });

      //添加图标组到地图
      this.map.add(markerList);

      //添加canvas图层------------------
      var canvas = document.createElement("canvas");
      canvas.width = canvas.height = 200;

      var context = canvas.getContext("2d");
      context.fillStyle = "rgb(0,100,255)";
      context.strokeStyle = "white";
      context.globalAlpha = 1;
      context.lineWidth = 2;

      var CanvasLayer = new self.AMap.CanvasLayer({
        canvas: canvas,
        bounds: new self.AMap.Bounds(
          [114.072202, 22.64473],
          [114.172202, 22.74473]
        ),
        zooms: [3, 18],
      });

      var radious = 0;
      var draw = function () {
        context.clearRect(0, 0, 200, 200);
        context.globalAlpha = (context.globalAlpha - 0.01 + 1) % 1;
        radious = (radious + 1) % 100;

        context.beginPath();
        context.arc(100, 100, radious, 0, 2 * Math.PI);
        context.fill();
        context.stroke();

        //2D视图时可以省略
        CanvasLayer.reFresh();

        self.AMap.Util.requestAnimFrame(draw);
      };
      let canvasobj = {
        canvas: null,
      };
      self.AMap.CanvasLayer(canvasobj);

      CanvasLayer.setMap(self.map);
      draw();
    },
  },
};
</script>
<style lang="scss">
.home-map-container{
    height: 100%;
}
</style>